package top.maof.lightsearch.map;

import top.maof.lightsearch.exception.NoMappingException;

import java.util.*;

public class MappingPool {
    private final static Mapping INT_MAPPING = new IntMapping();
    private final static Mapping LONG_MAPPING = new LongMapping();
    private final static Mapping DOUBLE_MAPPING = new DoubleMapping();
    private final static Mapping FLOAT_MAPPING = new FloatMapping();
    private final static Mapping STRING_MAPPING = new StringMapping();
    private final static Mapping BOOLEAN_MAPPING = new BooleanMapping();

    private final static Mapping LIST_MAPPING = new ListMapping();

    private final static Mapping SET_MAPPING = new SetMapping();

    private static Map<Class, Mapping> map = new HashMap<Class, Mapping>();

    static {
        map.put(int.class, INT_MAPPING);
        map.put(Integer.class, INT_MAPPING);

        map.put(long.class, LONG_MAPPING);
        map.put(Long.class, LONG_MAPPING);

        map.put(boolean.class, BOOLEAN_MAPPING);
        map.put(Boolean.class, BOOLEAN_MAPPING);

        map.put(Double.class, DOUBLE_MAPPING);
        map.put(double.class, DOUBLE_MAPPING);

        map.put(Float.class, FLOAT_MAPPING);
        map.put(float.class, FLOAT_MAPPING);

        map.put(String.class, STRING_MAPPING);

        map.put(List.class, LIST_MAPPING);
        map.put(ArrayList.class, LIST_MAPPING);
        map.put(LinkedList.class, LIST_MAPPING);

        map.put(HashSet.class, SET_MAPPING);
        map.put(TreeSet.class, SET_MAPPING);
    }

    public static Map<Class, Mapping> getPool() {
        return map;
    }

    public static Mapping getMapping(Class clazz) throws NoMappingException {
        Mapping mapping = map.get(clazz);
        if (mapping == null) {
            try {
                Object o = clazz.newInstance();
                if (o instanceof Set) {
                    return SET_MAPPING;
                } else if (o instanceof List) {
                    return LIST_MAPPING;
                }
            } catch (Exception e) {
            }

        }
        if (mapping == null) {
            throw new NoMappingException();
        }
        return mapping;
    }
}
